package com.example.springblog.controller;

import java.util.Map;
import java.util.HashMap;

import com.example.springblog.constants.Constant;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.UserService;
import com.example.springblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String username,String password) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail("账号或者密码错误");
        }
        UserInfo userInfo = userService.queryByName(username);
        if (userInfo==null || userInfo.getId()<0) {
            return Result.fail("用户不存在");
        }
        if (!password.equals(userInfo.getPassword())) {
            return Result.fail("密码错误");
        }
        Map<String,Object> claim = new HashMap<>();
        claim.put("id",userInfo.getId());
        claim.put("name",userInfo.getUserName());
        String token = JwtUtils.genToken(claim);
        return Result.success(token);
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        String token = request.getHeader(Constant.USER_TOKEN_HEADER);
        Integer userId = JwtUtils.getUserInfoFromToken(token);
        if (userId == null || userId < 0) return null;
        UserInfo userInfo = null;
        userInfo = userService.queryById(userId);
        userInfo.setPassword("");
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        if (blogId == null || blogId < 0) return null;
        UserInfo userInfo = userService.getAuthorInfoByBlogId(blogId);
        userInfo.setPassword("");
        return userInfo;
    }

    @RequestMapping("/isAuthor")
    public Result isAuthor(HttpServletRequest request,Integer blogId) {
        String token = request.getHeader(Constant.USER_TOKEN_HEADER);
        Integer userId = JwtUtils.getUserInfoFromToken(token);
        UserInfo userInfo = userService.getAuthorInfoByBlogId(blogId);
        if (userId == userInfo.getId()) return Result.success(true);
        else return Result.success(false);
    }
}
